package cn.itcast.flink.examples;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * Author itcast
 * Date 2022/1/11 9:15
 * todo 接收socket的单词数据，并以空格进行单词拆分打印。
 * 开发步骤：
 * 1.获取流执行环境（获取环境）
 * 2.设置并行度等参数
 * 3.获取 socket 数据源，流数据
 * 4.将单词拆分（空格）
 * 5.将每个单词映射（Tuple2）
 * 6.对每个 tuple2 分组，keyBy
 * 7.对分组的数据求和
 * 8.打印输出
 * 9.执行流环境
 */
public class WordCountStream {
    public static void main(String[] args) throws Exception {
        //1.获取流执行环境（获取环境）
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //2.设置并行度等参数
        env.setParallelism(1);
        //3.获取 socket 数据源，流数据
        DataStreamSource<String> source = env.socketTextStream("node1", 9999);
        //4.将单词拆分（空格）
        source.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(word);
                }
            }
        })
        //5.将每个单词映射（Tuple2）
        .map(new MapFunction<String, Tuple2<String,Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return Tuple2.of(value,1);
            }
        })
        //6.对每个 tuple2 分组，keyBy
        .keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> value) throws Exception {
                return value.f0;
            }
        })
        //7.对分组的数据求和
        .sum(1)
        //8.打印输出
        .print();
        //9.执行流环境
        env.execute();
    }
}
